using System;
using System.Collections.Generic;
using System.Text;
using CodePlex.Resourceful.Amazon.S3;
using System.IO;

namespace CodePlex.Resourceful.CommandLine.Actions.S3
{
    public class DeleteObjects : BaseS3
    {
        public DeleteObjects() 
            : base("delete-objects", "Deletes S3 objects.", 
                ParameterInfo.Required("aws-key","AWS access key ID",DefaultAwsKey()),
                ParameterInfo.Required("aws-secret","AWS secret key",DefaultAwsSecret()),
                ParameterInfo.Required("bucket","S3 bucket"),
        

                ParameterInfo.Optional("key","If specified, single object to delete"),
                ParameterInfo.Optional("key-prefix","If specified, only objects starting with this prefix will be deleted")
                
              
            
            )
        {

        }


        protected override void GoS3(S3Connection connection, NameValuePairs parameters)
        {
           
                string bucket = parameters["bucket"];

                string key = parameters.GetIfExists("key");
                string keyPrefix = parameters.GetIfExists("key-prefix");

                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(keyPrefix)) 
                {
                    throw CodePlexException.Format("Cannot specify both key and key-prefix");
                }
               

                if (!string.IsNullOrEmpty(key)) 
                {
                    this.DeleteObject(connection, bucket, key);
                }
                else if (!string.IsNullOrEmpty(keyPrefix))
                {
                    foreach (Key k in connection.ListBucket(bucket, keyPrefix))
                    {
                        this.DeleteObject(connection, bucket, k.Name);

                    }

                }
                else
                {
                    foreach (Key k in connection.ListBucket(bucket))
                    {
                        this.DeleteObject(connection, bucket, k.Name);
                    }
                    Console.Out.WriteLine("Deleting bucket [{0}]...", bucket);
                    connection.DeleteBucket(bucket);
                    Console.Out.WriteLine("Deleted bucket [{0}]", bucket);
                }

        }

        private void DeleteObject(S3Connection connection, string bucket, string key)
        {
            Console.Out.WriteLine("Deleting object in bucket [{0}] with key [{1}]...", bucket, key);
            connection.DeleteObject(bucket, key);
            Console.Out.WriteLine("Deleted object in bucket [{0}] with key [{1}]", bucket, key);
        }

        

    }
}
